package com.janj.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;

import java.io.IOException;
import java.io.InputStream;

//自己定义的工具类 和 工具方法
public class MyBatisUitls {
    private static InputStream is = null ;
    private static SqlSession session = null ;

    //构造方法私有化修饰，不让其他类创建该类对象


    private MyBatisUitls(){

    }

   //1.获取到执行者对象 session 用于执行SQL语句
    public static SqlSession getSQLSession(){
        try {
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            session = factory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return session ;
    }
    //释放资源

    public static void close(){
        try {
            if(is != null) {
                is.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        if(session != null) {
            session.close();
        }
    }
}
